#region License

// This file is part of Grawlix.
// 
// Grawlix is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
// Grawlix is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public
// License along with Grawlix.  If not, see
// <http://www.gnu.org/licenses/>.

#endregion

using System;

namespace Grawlix.Services.Resources
{
	/// <summary>
	/// A convenience base class for resource factories.
	/// </summary>
	/// <typeparam name="TDeclare">The type of resource the factory
	/// declares that it produces.</typeparam>
	/// <typeparam name="TDefine">The actual type of resource the
	/// factory produces.</typeparam>
	[Serializable]
	public abstract class AbstractResourceFactory<TDeclare,
	                                              TDefine> :
	                                              	ServiceBase
	                                              		<
	                                              		IDynamicResourceFactory
	                                              		<TDeclare>>,
	                                              	IDynamicResourceFactory
	                                              		<TDeclare>
		where TDeclare : IDynamicResource
		where TDefine : AbstractResourceProxy<TDeclare, TDefine>,
			TDeclare
	{
		/// <summary>
		/// The internal data store.
		/// </summary>
		private readonly ResourceRepository<TDeclare, TDefine>
			_repository;

		/// <summary>
		/// A translator for URIs.
		/// </summary>
		private readonly IUriResolver _uriResolver;

		/// <summary>
		/// Registers the needed services.
		/// </summary>
		/// <param name="uriResolver">A service used to complete URIs.
		/// </param>
		/// <exception cref="ArgumentNullException"><c>uriResolver</c>
		/// is null.</exception>
		protected AbstractResourceFactory(
			IUriResolver uriResolver)
		{
			if (uriResolver == null)
				throw new ArgumentNullException("uriResolver");
			_uriResolver = uriResolver;
			_repository =
				new ResourceRepository<TDeclare, TDefine>(this);
		}

		/// <summary>
		/// Access to the object which creates new resource proxies.
		/// </summary>
		/// <value>The creator of new proxies.</value>
		protected internal abstract
			AbstractResourceProxyCreator<TDeclare, TDefine> Creator { get; }

		/// <summary>
		/// Gets the URI resolver.
		/// </summary>
		/// <value>A translator for URIs.</value>
		protected IUriResolver UriResolver
		{
			get { return _uriResolver; }
		}

		/// <summary>
		/// Cancels the load of the specified resource.
		/// </summary>
		/// <param name="identifier">The URI of the resource to cancel.
		/// </param>
		protected internal abstract void CancelLoad(Uri identifier);

		/// <summary>
		/// Queues reloading of the specified resource.
		/// </summary>
		/// <param name="resource">The resource to reload.</param>
		/// <exception cref="ArgumentNullException"><c>resource</c> is
		/// null.</exception>
		public void Reload(TDeclare resource)
		{
			var typedResource = resource as TDefine;
			if (typedResource == null)
				throw new ArgumentNullException("resource");
			_repository.Reload(typedResource.Identifier);
			GC.KeepAlive(typedResource);
		}

		/// <summary>
		/// Finds and returns the specified resource.
		/// </summary>
		/// <param name="identifier">The URI of the resource to locate.
		/// </param>
		/// <returns>The new or cached resource.</returns>
		/// <exception cref="ArgumentNullException"><c>identifier</c>
		/// is null.</exception>
		public TDeclare Resolve(Uri identifier)
		{
			if (identifier == null)
				throw new ArgumentNullException("identifier");
			identifier = _uriResolver.CompleteUri(identifier);
			return
				ResourceRepository<TDeclare, TDefine>.GetCache(
					_repository).Find(identifier);
		}

		/// <summary>
		/// Switches in the state of a resource object.
		/// </summary>
		/// <param name="identifier">The identifier of the resource.
		/// </param>
		/// <param name="state">The state object.</param>
		/// <param name="loadFailed">if set to <c>true</c> mark the
		/// load as failed.</param>
		/// <remarks>This function may only be invoked during an 
		/// <see cref="UpdateState"/> call.</remarks>
		/// <exception cref="ArgumentNullException"><c>identifier</c>is
		/// null.</exception>
		/// <exception cref="InvalidOperationException">Attempt to
		/// update outside of an <see cref="UpdateState"/> call.
		/// </exception>
		/// <exception cref="ArgumentException">Attempt to update a
		/// nonexistent identifier.</exception>
		/// <exception cref="ArgumentException">Both state is not null
		/// and <paramref name="loadFailed"/> is true.</exception>
		protected void SetState(Uri identifier, object state,
		                        bool loadFailed)
		{
			_repository.SetState(identifier, state, loadFailed);
		}

		/// <summary>
		/// Starts the load of the resource with the given URI.
		/// </summary>
		/// <param name="identifier">The identifier of the resource to
		/// load.</param>
		protected internal abstract void StartLoad(Uri identifier);

		/// <summary>
		/// Starts the unload of the given state information.
		/// </summary>
		/// <param name="state">The state information to unload.</param>
		protected internal abstract void StartUnload(object state);

		/// <summary>
		/// Updates the factory based upon elapsed time.
		/// </summary>
		/// <param name="elapsed">The elapsed time since last update.
		/// </param>
		public void Update(TimeSpan elapsed)
		{
			_repository.Update(elapsed);
		}

		/// <summary>
		/// Updates the state.
		/// </summary>
		/// <param name="elapsed">The elapsed time since last update.
		/// </param>
		protected internal abstract void UpdateState(
			TimeSpan elapsed);
	}
}